//
//  XDTopupViewController.m
//  xindailianmeng
//
//  Created by 张东 on 2017/3/1.
//  Copyright © 2017年 xindailianmeng.cn. All rights reserved.
//

#import "XDTopupViewController.h"
#import "ZHRTBasicMethod.h"
#import "ZHRTRequestFailureShowViewOrDetail.h"
#import "AFHTTPSessionManager+POST.h"

@interface XDTopupViewController ()<UITextFieldDelegate>
@property (nonatomic, copy) NSString *previousTextFieldContent;

@property (nonatomic, weak) UITextField  *iphoneNo;

@property (nonatomic, weak) UITextField  *checkTf;

@property (nonatomic, weak) UIButton  *nextBtn;

@property (nonatomic ,weak) UIButton *clearBtn;

@property (nonatomic, weak) UIButton *checkCodeBtn;

@property (nonatomic, strong)NSTimer *timer;

@property (nonatomic, assign) NSInteger count;
//orderNo  订单号 String（用来判断是不是重发短信）
@property (nonatomic, copy) NSString  *orderNo;


@property (nonatomic, weak) UIView *alertView;

@property (nonatomic, weak) UIButton *titleBtn;

@property (nonatomic, weak) UILabel *messageLb;
@end

@implementation XDTopupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = kColorRGB(234, 234, 234);
    
    self.title = @"充值";
    
    [self setupUI];

}
- (void)setupUI {
    
    UITextField *iphoneNo = [self createTextFieldWithFrame:CGRectMake(0, 10, kScreenW, 50) textFont:kBaseFont_(14) textColor:kColorRGB(51, 51, 51) placeholder:@"请输入银行预留手机号" placeholderFont:kBaseFont_(13) leftTitle:@"手机号" delegate:self inView:self.view style:0];
    self.iphoneNo = iphoneNo;
    
    UITextField *checkTf = [self createTextFieldWithFrame:CGRectMake(0, CGRectGetMaxY(iphoneNo.frame) + 10, kScreenW, 50) textFont:kBaseFont_(14) textColor:kColorRGB(51, 51, 51) placeholder:@"请输入验证码" placeholderFont:kBaseFont_(13) leftTitle:@"验证码" delegate:self inView:self.view style:1];
    self.checkTf = checkTf;
    
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake((kScreenW - 240) / 2, CGRectGetMaxY(checkTf.frame) + 38, 240, 40)];
    [nextBtn setImage:[UIImage imageNamed:@"sure_topup_nor"] forState:UIControlStateDisabled];
    nextBtn.enabled = NO;
    [nextBtn setImage:[UIImage imageNamed:@"sure_topup_height"] forState:UIControlStateNormal];
    [nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.nextBtn = nextBtn;
    [self.view addSubview:nextBtn];
    
    self.count = 60;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerDidClick) userInfo:nil repeats:YES];
    [_timer setFireDate:[NSDate distantFuture]];
    
}

- (UITextField *)createTextFieldWithFrame:(CGRect)frame textFont:(UIFont *)textFont textColor:(UIColor *)textColor placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont leftTitle:(NSString *)leftTitle delegate:(id)obj inView:(UIView *)inView style:(NSInteger)style {
    
    UITextField *textField = [[UITextField alloc] initWithFrame:frame];
    textField.background = [UIImage imageNamed:@"textfield-1"];
    textField.textAlignment = NSTextAlignmentRight;
    textField.textColor =  textColor;
    textField.font = textFont;
    textField.attributedPlaceholder = [self textFieldAttributedPlaceholderWith:textField placeholder:placeholder placeholderFont:placeholderFont];
    textField.keyboardType = UIKeyboardTypeNumberPad;
    textField.delegate = self;
    [textField addTarget:self action:@selector(numberChange:) forControlEvents:UIControlEventEditingChanged];
    
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 80, 48)];
    leftView.backgroundColor = [UIColor whiteColor];
    
    UILabel *nameLb = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 80, 48)];
    nameLb.text = leftTitle;
    nameLb.textColor = kColorRGB(102,102,102);
    nameLb.font = kBaseFont_(14);
    nameLb.textAlignment = NSTextAlignmentLeft;
    [leftView addSubview:nameLb];
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    
    
    if (style == 0) {
        UIButton *clearBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 1, 15, 48)];
        self.clearBtn = clearBtn;
        clearBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        clearBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 0);
        [clearBtn addTarget:self action:@selector(clearBtnClick) forControlEvents:UIControlEventTouchUpInside];
        clearBtn.enabled = NO;
        textField.rightView = clearBtn;
    } else  if (style == 1){
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 1, 115, 48)];
        
        UIButton *checkCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 11.5, 90, 25)];
        [checkCodeBtn setBackgroundImage:[UIImage imageNamed:@"check_dis"] forState:UIControlStateDisabled];
        checkCodeBtn.enabled = NO;
        [checkCodeBtn setBackgroundImage:[UIImage imageNamed:@"check_nor"] forState:UIControlStateNormal];
        [checkCodeBtn addTarget:self action:@selector(checkCodeBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [checkCodeBtn setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
        [view addSubview:checkCodeBtn];
        self.checkCodeBtn = checkCodeBtn;
        textField.rightView = view;
    }
    
    textField.rightViewMode = UITextFieldViewModeAlways;
    
    [inView addSubview:textField];
    return textField;
}

//修改UITextField的placeholder字体并垂直居中
- (NSAttributedString *)textFieldAttributedPlaceholderWith:(UITextField *)textField placeholder:(NSString *)placeholder placeholderFont:(UIFont *)placeholderFont  {
    if (placeholder) {
        NSMutableParagraphStyle *style = [textField.defaultTextAttributes[NSParagraphStyleAttributeName] mutableCopy];
        style.minimumLineHeight = textField.font.lineHeight - (textField.font.lineHeight - placeholderFont.lineHeight) / 2.0;
        NSAttributedString *attr = [[NSAttributedString alloc] initWithString:placeholder attributes:@{NSFontAttributeName:placeholderFont, NSParagraphStyleAttributeName : style}];
        return attr;
    }
    return nil;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    
    self.previousTextFieldContent = textField.text;
    return YES;
}
- (void)numberChange:(UITextField *)textField
{

    if (textField == self.iphoneNo) {
    if (textField.text.length > 0) {
        
        
        self.clearBtn.frame = CGRectMake(0, 1, 40, 48);
        self.clearBtn.enabled = YES;
        [self.clearBtn setImage:[UIImage imageNamed:@"cancal_my"] forState:UIControlStateNormal];
        
    } else {
        
        self.clearBtn.frame = CGRectMake(0, 1, 15, 48);
        self.clearBtn.enabled = NO;
        [self.clearBtn setImage:nil forState:UIControlStateNormal];
    }
    
    //限制手机账号长度（有两个空格）
    if (textField.text.length > 13) {
        textField.text = [textField.text substringToIndex:13];
    }
    
    NSUInteger targetCursorPosition = [textField offsetFromPosition:textField.beginningOfDocument toPosition:textField.selectedTextRange.start];
    
    NSString *currentStr = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *preStr = [self.previousTextFieldContent stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    //正在执行删除操作时为0，否则为1
    char editFlag = 0;
    if (currentStr.length <= preStr.length) {
        editFlag = 0;
    }
    else {
        editFlag = 1;
    }
    
    NSMutableString *tempStr = [NSMutableString new];
    
    int spaceCount = 0;
    if (currentStr.length < 3 && currentStr.length > -1) {
        spaceCount = 0;
    }else if (currentStr.length < 7 && currentStr.length > 2) {
        spaceCount = 1;
    }else if (currentStr.length < 12 && currentStr.length > 6) {
        spaceCount = 2;
    }
    
    for (int i = 0; i < spaceCount; i++) {
        if (i == 0) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(0, 3)], @" "];
        }else if (i == 1) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(3, 4)], @" "];
        }else if (i == 2) {
            [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
        }
    }
    
    if (currentStr.length == 11) {
        [tempStr appendFormat:@"%@%@", [currentStr substringWithRange:NSMakeRange(7, 4)], @" "];
    }
    if (currentStr.length < 4) {
        [tempStr appendString:[currentStr substringWithRange:NSMakeRange(currentStr.length - currentStr.length % 3, currentStr.length % 3)]];
    }else if(currentStr.length > 3 && currentStr.length <12) {
        NSString *str = [currentStr substringFromIndex:3];
        [tempStr appendString:[str substringWithRange:NSMakeRange(str.length - str.length % 4, str.length % 4)]];
        if (currentStr.length == 11) {
            [tempStr deleteCharactersInRange:NSMakeRange(13, 1)];
        }
    }
    textField.text = tempStr;
    // 当前光标的偏移位置
    NSUInteger curTargetCursorPosition = targetCursorPosition;
    
    if (editFlag == 0) {
        //删除
        if (targetCursorPosition == 9 || targetCursorPosition == 4) {
            curTargetCursorPosition = targetCursorPosition - 1;
        }
    }else {
        //添加
        if (currentStr.length == 8 || currentStr.length == 4) {
            curTargetCursorPosition = targetCursorPosition + 1;
        }
    }
    UITextPosition *targetPosition = [textField positionFromPosition:[textField beginningOfDocument] offset:curTargetCursorPosition];
    [textField setSelectedTextRange:[textField textRangeFromPosition:targetPosition toPosition :targetPosition]];
    
        NSString * phone = [self.iphoneNo.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        if (phone.length == 11) {
            
            
            if (![ZHRTBasicMethod isMobileNumber:phone]) {
                
                [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入正确的手机号" view:self.view];
            } else {
                
                self.checkCodeBtn.enabled = YES;
            }
            
        }else {
            self.checkCodeBtn.enabled = NO;
            self.count = 60;
            [self.checkCodeBtn setBackgroundImage:[UIImage imageNamed:@"check_dis"] forState:UIControlStateDisabled];
            [self.checkCodeBtn setTitle:@"" forState:UIControlStateDisabled];
            [self.timer setFireDate:[NSDate distantFuture]];
        }
        
        
        if (phone.length == 11 && self.checkTf.text.length == 6) {
            if (![ZHRTBasicMethod isMobileNumber:phone]) {
                [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入正确的手机号" view:self.view];
            } else {
                self.nextBtn.enabled = YES;
            }
        } else {
            
            self.nextBtn.enabled = NO;
        }
        
   
    }

//判断是否是手机号码

    else {
    
    if (self.checkTf.text.length > 6) {
        
        [ZHRTRequestFailureShowViewOrDetail showViewDetail:@"请输入正确的验证码" view:self.view];
        
        self.checkTf.text = [self.checkTf.text substringToIndex:6];
    }
        if (self.checkTf.text.length == 6) {
        
            self.nextBtn.enabled = YES;
            
        } else {
            
            self.nextBtn.enabled = NO;
            
        }
        
        
    }
}
- (void)checkCodeBtnClick {
    
    NSLog(@"获取验证码");
    [self.timer setFireDate:[NSDate distantPast]];
    [self getMobileCode];
    [self.checkCodeBtn setBackgroundImage:[UIImage imageNamed:@"backGrourd_timer-1"] forState:UIControlStateDisabled];
    
}
// timer
- (void)timerDidClick {
    _count -= 1;
    [self.checkCodeBtn setTitle:[NSString stringWithFormat:@"%lds", (long)_count] forState:UIControlStateDisabled];
    self.checkCodeBtn.enabled = NO;
    if (_count == 0) {
        [self againSMSVerify];
        self.checkCodeBtn.enabled = YES;
    }
}
// 验证请求失败后重新发送设置
- (void)againSMSVerify {
    _count = 60;
    [_timer setFireDate:[NSDate distantFuture]];
    [self.checkCodeBtn setTitle:@"" forState:UIControlStateNormal];
    [self.checkCodeBtn setBackgroundImage:[UIImage imageNamed:@"Recheck"] forState:UIControlStateNormal];
    self.checkCodeBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    self.checkCodeBtn.enabled = YES;
}


//获取验证码
- (void)getMobileCode
{
    
    if (!self.orderNo) {
         self.orderNo = @"";
    }
    NSString *text = [self.iphoneNo.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSString *amount = [self.amount stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSDictionary *param = @{@"method":@"depositApply",@"userMobile":text,@"bankId":self.bankId,@"amount":amount,@"orderNo":self.orderNo};
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject)
     {
        
         
         if ([responseObject[@"code"] isEqualToString:@"100000"])
         {
             
             self.orderNo = responseObject[@"result"][@"orderNo"];
             
         } else {
             [ZHRTRequestFailureShowViewOrDetail showViewDetail:responseObject[@"message"] view:self.view];
             [self againSMSVerify];
         }
         
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         [self againSMSVerify];
     }];
}

- (void)nextBtnClick {
 
//    [self againSMSVerify];
    if (!self.orderNo) {
        self.orderNo = @"";
    }
    NSString *text = [self.iphoneNo.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *checkCode = [self.checkTf.text stringByReplacingOccurrencesOfString:@" " withString:@""];
     NSString *amount = [self.amount stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSDictionary *param = @{
        @"method":@"depositConfirm",
        @"userMobile":text,
        @"bankId": self.bankId,
        @"amount":amount,
        @"orderNo":self.orderNo,
        @"checkCode": checkCode
            };
    [AFHTTPSessionManager POSTWithParams:param success:^(NSURLSessionDataTask *task, id responseObject)
     {
         if ([responseObject[@"code"] isEqualToString:@"100000"])
         {
             
             /*
              
              {
              "type": "success",
              "code": "100000",
              "message": "操作成功",
              "result": {
              "msg": "2017/03/01 16:16:23",
              "amount": "￥1,000.00",
              "orderNo": "CZ170301161547c"
              }
              }
              
              */
             NSString *amount = [responseObject[@"result"][@"amount"] stringByReplacingOccurrencesOfString:@"￥" withString:@""];
             NSString *msgStr = [NSString stringWithFormat:@"您已成功充值%@元",amount];
             NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:msgStr];
             
             [attr addAttribute:NSForegroundColorAttributeName value:kColorRGB(51, 51, 51) range:[msgStr rangeOfString:amount]];
              [self alertViewWithMessage:attr imageNamed:@"succeed_my" btnTitle:@"充值成功" text:@"立刻投资赚钱吧" image:@"more_next" tag:0];
           
             
         } else {
             
             
             [self alertViewWithMessage:[[NSAttributedString alloc] initWithString:responseObject[@"message"]] imageNamed:@"fail_my" btnTitle:@"充值失败" text:@"我知道了" image:nil tag:1];

         }
         
     } failure:^(NSURLSessionDataTask *task, NSError *error) {
         
     }];
}


- (void)clearBtnClick {
    
    self.iphoneNo.text = nil;
    
    self.clearBtn.frame = CGRectMake(0, 1, 15, 48);
    self.clearBtn.enabled = NO;
    [self.clearBtn setImage:nil forState:UIControlStateNormal];
   
}

- (void)alertViewWithMessage: (NSAttributedString *)msg imageNamed:(NSString *)imageNamed  btnTitle:(NSString *)btnTitle  text:(NSString *)text image: (NSString *)image tag:(NSInteger)tag{
    
    if (_alertView == nil) {
        
        UIView *alertView = [[UIView alloc] initWithFrame:kScreenB];
        alertView.alpha = 0;
        alertView.backgroundColor = kColorRGBA(0, 0, 0, 0.5);
        _alertView = alertView;
        [self.view addSubview:alertView];
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(52 * kscaleW, 136 * kscale, kScreenW - 52 * kscaleW * 2, 133)];
        
        view.backgroundColor = [UIColor whiteColor];
        view.layer.cornerRadius = 10;
        view.layer.masksToBounds = YES;
        [alertView addSubview:view];
        
        UIButton *titleBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, view.frame.size.width, 30)];
        [titleBtn setTitleColor:kColorRGB(51, 51, 51) forState:UIControlStateDisabled];
        titleBtn.titleLabel.font = kBaseFont_(17);
        titleBtn.enabled = NO;
        [titleBtn setImage:[UIImage imageNamed:imageNamed] forState:UIControlStateDisabled];
        [titleBtn setTitle:btnTitle forState:UIControlStateDisabled];
        self.titleBtn = titleBtn;
        [view addSubview:titleBtn];
        
        UILabel *messageLb = [[UILabel alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(titleBtn.frame) + 10, view.frame.size.width - 30 , 20)];
       
        messageLb.textColor = kColorRGB(102, 102, 102);
        
        messageLb.font = kBaseFont_(12);
        messageLb.numberOfLines = 0;
        messageLb.attributedText = msg;
        messageLb.textAlignment =NSTextAlignmentCenter;
        [messageLb sizeToFit];
        self.messageLb = messageLb;
        [view addSubview:messageLb];
        CGFloat viewW = view.frame.size.width;
        CGFloat messageLbW = messageLb.frame.size.width;
        messageLb.frame = CGRectMake((viewW - messageLbW) * 0.5, CGRectGetMaxY(titleBtn.frame) + 10, messageLb.frame.size.width, messageLb.frame.size.height);
      
        UIView *carveView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(messageLb.frame) + 20, view.frame.size.width, 0.5)];
        carveView.backgroundColor = kColorRGBA(0, 0, 0, 0.2);
        [view addSubview:carveView];
        
      
        
        UIButton *knowBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(carveView.frame), view.frame.size.width, 42)];
        [knowBtn setTitle:text forState:UIControlStateNormal];
        [knowBtn setTitleColor:kColorRGB(187,147,115) forState:UIControlStateNormal];
        if (tag == 0) {
            
            [knowBtn setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
            
        }
        knowBtn.titleLabel.font = kBaseFont_(15);
        [knowBtn addTarget:self action:@selector(knowBtnClick) forControlEvents:UIControlEventTouchUpInside];
        knowBtn.tag = tag;
        [view addSubview:knowBtn];
        
        view.frame = CGRectMake(52 * kscaleW, 136 * kscale, kScreenW - 52 * kscaleW * 2, CGRectGetMaxY(knowBtn.frame));
        
        [UIView animateWithDuration:0.5 animations:^{
            alertView.alpha = 1;
        }];
    }
}

- (void)knowBtnClick {
    
    [self.alertView removeFromSuperview];
    
    self.tabBarController.selectedIndex = 1;
    [self.navigationController popToRootViewControllerAnimated:NO];
}

@end
